const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');
const bodyParser = require('body-parser');
const sequelize = require('./config/database');
const Job = require('./models/Job');
const Resume = require('./models/Resume');

const app = express();
app.use(cors());
app.use(bodyParser.json());

// 同步所有模型到数据库
sequelize.sync({ alter: true }) // alter:true会自动调整表结构，生产环境建议用sync({ force: false })
  .then(() => {
    console.log('所有模型已同步到数据库');
  })
  .catch(err => {
    console.error('模型同步失败:', err);
  });

// 新增职位
app.post('/api/jobs', (req, res) => {
  const job = req.body;
  const sql = `INSERT INTO jobs (title, industry, description, salary_range, requirements, location, job_type, experience, education, benefits, highlights, company_intro)
               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
  db.query(sql, [
    job.title, job.industry, job.description, job.salary_range, job.requirements,
    job.location, job.job_type, job.experience, job.education, job.benefits, job.highlights, job.company_intro
  ], (err, result) => {
    if (err) return res.status(500).json({ error: err.message });
    res.json({ id: result.insertId, ...job });
  });
});

// 获取所有职位
app.get('/api/jobs', (req, res) => {
  db.query('SELECT * FROM jobs ORDER BY id DESC', (err, results) => {
    if (err) return res.status(500).json({ error: err.message });
    res.json(results);
  });
});

// 获取单个职位详情
app.get('/api/jobs/:id', (req, res) => {
  db.query('SELECT * FROM jobs WHERE id = ?', [req.params.id], (err, results) => {
    if (err) return res.status(500).json({ error: err.message });
    if (results.length === 0) return res.status(404).json({ error: '未找到该职位' });
    res.json(results[0]);
  });
});

// 删除职位
app.delete('/api/jobs/:id', (req, res) => {
  db.query('DELETE FROM jobs WHERE id = ?', [req.params.id], (err, result) => {
    if (err) return res.status(500).json({ error: err.message });
    res.json({ success: true });
  });
});

// 启动服务
app.listen(3001, () => {
  console.log('后端服务已启动，端口3001');
});